package com.ankiang.treeprint.fragment.components;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.lib.annotation.Widget;
import com.ankiang.treeprint.manager.QDDataManager;
import com.ankiang.treeprint.model.TRItemTree;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.view.TRListener;
import com.ankiang.treeprint.view.TRConfig;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * {@link QMUIGroupListView} 的使用示例。
 * Created by Kayo on 2016/11/21.
 */

@Widget(widgetClass = TRSearchItemFragment.class, iconRes = R.mipmap.icon_grid_group_list_view)
public class TRSearchItemFragment extends BaseFragment {

    public static final int SEARCH_READ = 1; // 搜索查看
    public static final int SEARCH_SELECT = 2; // 搜索选择
    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.groupListView)
    QMUIGroupListView mGroupListView;

    @BindView(R.id.search_keyword)
    TextView keywordTextView;


    @BindView(R.id.sort_type)
    ImageButton orderTypeImageButton;


    static final int ORDER_TYPE_TIME = 0;
    static final int ORDER_TYPE_ALPHA = 1;
    int orderType;


    TRListener searchCallBack;

    private QDDataManager.QDItemDescription mQDItemDescription;

    // 保存数据
    private TRItemTree itemTree;


    // 配置
    private TRConfig conf;
    private int mOp = SEARCH_SELECT;

    // 设置选择还是查看
    public void setOp(int mOp) {
        this.mOp = mOp;
    }

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.tr_fragment_search_item, null);
        ButterKnife.bind(this, root);

        conf = TRConfig.getInstance();


        mQDItemDescription = QDDataManager.getInstance(getContext()).getDescription(this.getClass());
        initTopBar();

        initGroupListView();

        initListener();

        return root;
    }

    private void initListener() {
        keywordTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mGroupListView.removeAllViews();
                showResultList();
            }
        });

        orderTypeImageButton.setOnClickListener(v -> {
            orderType = (orderType + 1) % 2;
            showResultList();
        });
    }

    private void showResultList() {

        if (this.itemTree == null) {
            return;
        }


        final View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = (int) v.getTag();

                if (mOp == SEARCH_READ) {
                    TRAddItemFragment fragment = new TRAddItemFragment();
                    fragment.setOp(TRAddItemFragment.EDIT);
                    TRItemNode data = itemTree.get(id);
                    Bundle bundle = new Bundle();
                    bundle.putInt(TRAddItemFragment.KEY_TAG, TRAddItemFragment.TAG_DETAILS);
                    bundle.putSerializable(TRAddItemFragment.KEY_DATA, data);
                    bundle.putSerializable(TRAddItemFragment.KEY_OTHER_DATA, null);
                    fragment.setArguments(bundle);
//                    fragment.setItemId(id);
                    fragment.setItemTree(itemTree);
                    startFragment(fragment);
                } else if (mOp == SEARCH_SELECT) {
                    if (searchCallBack != null) {
                        searchCallBack.afterOperation(id);
                    }
                    popBackStack();
                }
            }
        };
        mGroupListView.removeAllViews();

        QMUIGroupListView.Section list = QMUIGroupListView.newSection(getContext());
//                .setTitle(V(R.string.search));

        TRItemNode item;
        QMUICommonListItemView itemView;
        String kw = keywordTextView.getText().toString();
        if (mOp == SEARCH_SELECT && kw.equals("")) {
            itemView = mGroupListView.createItemView(V(R.string.search_no_item));
            item = new TRItemNode();
            item.setId(0);
            itemView.setTag(0);
            itemView.setOrientation(QMUICommonListItemView.HORIZONTAL);
            list.addItemView(itemView, onClickListener);
        }


        List<TRItemNode> tList = new ArrayList<>();
        Iterator<TRItemNode> iter = itemTree.values().iterator();
        while (iter.hasNext()) {
            item = iter.next();
            tList.add(item);
        }
        if (orderType == ORDER_TYPE_ALPHA) {
            orderTypeImageButton.setImageResource(R.drawable.ic_order_alpha);
            // 根据的查看时间顺序排序
            Collections.sort(tList, (a, b) -> {
                if (a == null) {
                    return -1;
                }
                if (b == null) {
                    return 1;
                }

                Collator collator = Collator.getInstance(Locale.CHINA);
                return collator.getCollationKey(a.getCallname())
                        .compareTo(collator.getCollationKey(b.getCallname()));

            });
        } else {
            // 根据的插入时间倒序排序
            orderTypeImageButton.setImageResource(R.drawable.ic_order_time);
            Collections.sort(tList, (o2, o1) -> {
                if (o1 == null || o1.getUpdatetime() == null) {
                    return 1;
                }

                if (o2 == null || o2.getUpdatetime() == null) {
                    return -1;
                }

                Collator collator = Collator.getInstance(Locale.CHINA);
                return collator.getCollationKey(o1.getUpdatetime())
                        .compareTo(collator.getCollationKey(o2.getUpdatetime()));
            });
        }

        iter = tList.iterator();
        while (iter.hasNext()) {
            item = iter.next();
            String callname = item.getCallname();
            String name = item.getName();

            if (item.match(kw)) {
                itemView = mGroupListView.createItemView(callname);
                itemView.setTag(item.getId());
                itemView.setOrientation(QMUICommonListItemView.HORIZONTAL);
                itemView.setDetailText(name);

                Drawable x = conf.getSexImgDrawable(getContext(), item.getSex());
                itemView.setImageDrawable(x);

                list.addItemView(itemView, onClickListener);
            }
        }
        list.addTo(mGroupListView);
    }

    private void initTopBar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popBackStack();
            }
        });

        mTopBar.setTitle(mQDItemDescription.getName());
//        mTopBar.addRightTextButton(R.string.cancel, QMUIViewHelper.generateViewId())
//                .setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        popBackStack();
//                    }
//                });
    }


    private void initGroupListView() {
        showResultList();

    }

    public void setItemTree(TRItemTree itemTree) {
        this.itemTree = itemTree;
    }

    public void setSearchCallBack(TRListener searchCallBack) {
        this.searchCallBack = searchCallBack;
    }
}
